<?php

namespace App\Http\Controllers;

use App\Http\Resources\CustomerResource;
use App\Laravue\Models\customer;
use Dotenv\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CustomerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //
        $serach=$request->input('search');
        $media=$request->input('media');
        $list = customer::select('customers.*','users.name')
        ->leftJoin('users','users.id','=','customers.submituser')
        ->when($serach,function($query) use ($serach){
            return $query
                ->where('advertiser','like',"%$serach%")
                ->orwhere('contacts_name','like',"%$serach%")
                ->orwhere('contacts_tel','like',"%$serach%")
                ->orwhere('name','like',"%$serach%")
                ;
        })->when($media,function($q) use($media){
            return $q->where('type',$media);
            })
            ->paginate(15);

        return CustomerResource::collection($list);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //

        $validator =  $request->validate(
            [
                'advertiser' => ['required','unique:customers']
            ]
        );




        $params = $request->all();

        $customer = new customer($params);
        $customer->submituser = Auth::id();
        $customer->save();
        return new CustomerResource($customer);


    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Laravue\Models\customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function show(customer $customer)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Laravue\Models\customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function edit(customer $customer)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Laravue\Models\customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, customer $customer)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Laravue\Models\customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function destroy(customer $customer)
    {
        //
    }
}
